<template>
  <div class="divBox">
    <el-card class="box-card">
      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="商户名称111">
          <el-input v-model="searchForm.mer_name" placeholder="请输入商户名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="联系人">
          <el-input v-model="searchForm.real_name" placeholder="请输入联系人" clearable></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.mer_phone" placeholder="请输入手机号" clearable></el-input>
        </el-form-item>
        <el-form-item label="关键字">
          <el-input v-model="searchForm.mer_keyword" placeholder="请输入关键字" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.is_conduct" placeholder="请选择状态" clearable>
            <el-option label="已通过" value="0"></el-option>
            <el-option label="待审核" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 商户列表 -->
      <el-table
        v-loading="tableLoading"
        :data="tableData"
        border
        style="width: 100%">
        <el-table-column
          prop="mer_id"
          label="商户ID"
          width="80">
        </el-table-column>
        <el-table-column
          prop="mer_avatar"
          label="Logo"
          width="80">
          <template slot-scope="scope">
            <el-image
              style="width: 40px; height: 40px"
              :src="scope.row.mer_avatar"
              fit="cover"
              :preview-src-list="[scope.row.mer_avatar]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column
          prop="mer_name"
          label="商户名称"
          min-width="120">
        </el-table-column>
        <el-table-column
          prop="real_name"
          label="联系人"
          width="100">
        </el-table-column>
        <el-table-column
          prop="mer_keyword"
          label="关键字"
          width="120">
        </el-table-column>
        <el-table-column
          prop="mer_phone"
          label="联系电话"
          width="120">
        </el-table-column>
        <el-table-column
          prop="mer_address"
          label="商户地址"
          min-width="200">
        </el-table-column>
        <el-table-column
          prop="turnover"
          label="营业额"
          width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.turnover !== undefined && scope.row.turnover !== null">
              ¥{{ formatMoney(scope.row.turnover) }}
            </span>
            <span v-else class="text-muted">暂无数据</span>
          </template>
        </el-table-column>
        <el-table-column
          label="状态"
          width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.is_conduct === 0" type="success">通过</el-tag>
            <el-tag v-else-if="scope.row.is_conduct === 2" type="danger">待审核</el-tag>
            <el-tag v-else type="info">其他</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="180"
          fixed="right">
          <template slot-scope="scope">
            <template v-if="scope.row.is_conduct === 2">
              <el-button
                type="text"
                size="small"
                @click="handleApprove(scope.row)">
                通过
              </el-button>
              <el-button
                type="text"
                size="small"
                @click="handleReject(scope.row)">
                拒绝
              </el-button>
            </template>
            <el-button
              v-if="scope.row.is_conduct === 0"
              type="text"
              size="small"
              @click="handleCancelRelation(scope.row)">
              取消关联
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getMerchantList, updateMerchantId, updateMerchantConduct, updateMerchantStatus } from '@/api/merchant'
import { getBaseInfo } from "@/api/user";

export default {
  name: 'MerchantList',
  data() {
    return {
      mer_id: '',
      is_conduct: '',
      is_mer_id: '',
      is_status: '',
      searchForm: {
        mer_name: '',
        real_name: '',
        mer_phone: '',
        mer_keyword: '',
        is_conduct: ''
      },
      tableLoading: false,
      tableData: [],
      page: 1,
      limit: 10,
      total: 0
    }
  },
  created() {
    this.getBaseInfo();
  },
  methods: {
    // 格式化金额显示
    formatMoney(amount) {
      if (amount === null || amount === undefined) return '0.00';
      return Number(amount).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      });
    },
    
    // 获取当前商户信息
    getBaseInfo() {
      getBaseInfo().then(res => {
      this.mer_id = res.data.mer_id;
      this.is_conduct = res.data.is_conduct;
      this.is_mer_id = res.data.is_mer_id;
      this.is_status = res.data.is_status;
        this.getList();
      }).catch(err => {
        this.$message.error('获取商户信息失败');
      });
    },
    
    // 获取列表数据
    async getList() {
      this.tableLoading = true;
      try {
        const params = {
          page: this.page,
          limit: this.limit,
          is_mer_id: this.mer_id, // 当前商户的子商户
          ...this.searchForm
        };
        console.log(params,'params');
        
        const res = await getMerchantList(params);
        if (res.status === 200) {
          this.tableData = res.data.list;
          this.total = res.data.count;
        } else {
          this.$message.error(res.msg || '获取数据失败');
        }
      } catch (error) {
        console.error('获取商户列表失败:', error);
        this.$message.error('获取数据失败');
      } finally {
        this.tableLoading = false;
      }
    },
    
    // 搜索
    handleSearch() {
      this.page = 1;
      this.getList();
    },
    
    // 重置搜索
    resetSearch() {
      this.searchForm = {
        mer_name: '',
        real_name: '',
        mer_phone: '',
        mer_keyword: '',
        is_conduct: ''
      };
      this.handleSearch();
    },
    
    // 分页
    handleSizeChange(val) {
      this.limit = val;
      this.getList();
    },
    
    handleCurrentChange(val) {
      this.page = val;
      this.getList();
    },
    
    // 取消关联
    handleCancelRelation(row) {
      this.$confirm('确定要取消关联吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用更新商户关联ID的API
        updateMerchantId(row.mer_id, {
          is_mer_id: 0 // 取消关联，设置为0
        }).then(res => {
          if (res.status === 200) {
            // 调用更新商户申请状态的API
            return updateMerchantConduct(row.mer_id, {
              is_conduct: 0 // 取消申请状态
            });
          } else {
            return Promise.reject(res);
          }
        }).then(res => {
          if (res.status === 200) {
            // 调用更新商户状态的API
            return updateMerchantStatus(row.mer_id, {
              is_status: 0 // 设置状态为0
            });
          } else {
            return Promise.reject(res);
          }
        }).then(res => {
          if (res.status === 200) {
            this.$message.success('取消关联成功');
            // 刷新列表
            this.getList();
          } else {
            this.$message.error(res.msg || '取消关联失败');
          }
        }).catch(err => {
          this.$message.error(err.msg || '取消关联失败');
        });
      }).catch(() => {
        this.$message.info('已取消操作');
      });
    },
    
    // 通过申请
    handleApprove(row) {
      this.$confirm('确定通过该商户的申请吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用更新商户申请状态的API
        updateMerchantConduct(row.mer_id, {
          is_conduct: 0 // 设置为通过
        }).then(res => {
          if (res.status === 200) {
            // 调用更新商户状态的API
            return updateMerchantStatus(row.mer_id, {
              is_status: 2 // 设置状态为2
            });
          } else {
            return Promise.reject(res);
          }
        }).then(res => {
          if (res.status === 200) {
            this.$message.success('已通过申请');
            // 刷新列表
            this.getList();
          } else {
            this.$message.error(res.msg || '操作失败');
          }
        }).catch(err => {
          this.$message.error(err.msg || '操作失败');
        });
      }).catch(() => {
        this.$message.info('已取消操作');
      });
    },
    
    // 拒绝申请
    handleReject(row) {
      this.$confirm('确定拒绝该商户的申请吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用更新商户关联ID的API
        updateMerchantId(row.mer_id, {
          is_mer_id: 0 // 清除关联ID
        }).then(res => {
          if (res.status === 200) {
            // 调用更新商户申请状态的API
            return updateMerchantConduct(row.mer_id, {
              is_conduct: 0 // 重置申请状态
            });
          } else {
            return Promise.reject(res);
          }
        }).then(res => {
          if (res.status === 200) {
            // 调用更新商户状态的API
            return updateMerchantStatus(row.mer_id, {
              is_status: 0 // 设置状态为0
            });
          } else {
            return Promise.reject(res);
          }
        }).then(res => {
          if (res.status === 200) {
            this.$message.success('已拒绝申请');
            // 刷新列表
            this.getList();
          } else {
            this.$message.error(res.msg || '操作失败');
          }
        }).catch(err => {
          this.$message.error(err.msg || '操作失败');
        });
      }).catch(() => {
        this.$message.info('已取消操作');
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.search-form {
  margin-bottom: 20px;
}
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
.text-muted {
  color: #909399;
  font-size: 12px;
}
</style>
